require('colors');
const moment = require('moment');

async function koa(ctx, next) {

    if (ctx.request._logging) {
        await next();
        return;
    }

    let start = new Date();
    await next();

    let code = ctx.res.statusCode;
    let str = `${ctx.method} ${code} ${new Date() - start}ms ${ctx.originalUrl}`;
    info(str);
    // debug(str);
    // warn(str);
    // error(str);
    // fatal(str);

    // if (code >= 300) this.warn()
    // if (code >= 400) level = levels.ERROR
}

function info(logs) {
    let time = moment().format('YYYY-MM-DD HH:mm:ss SSS');
    console.log(`[${time}] [INFO] - ${logs}`.white);
}

function debug(logs) {
    let time = moment().format('YYYY-MM-DD HH:mm:ss SSS');
    console.log(`[${time}] [DEBUG] - ${logs}`.cyan);
}

function warn(logs) {
    let time = moment().format('YYYY-MM-DD HH:mm:ss SSS');
    console.log(`[${time}] [WARN] - ${logs}`.yellow);
}

function error(logs) {
    let time = moment().format('YYYY-MM-DD HH:mm:ss SSS');
    console.log(`[${time}] [ERROR] - ${logs}`.red);
}

function fatal(logs) {
    let time = moment().format('YYYY-MM-DD HH:mm:ss SSS');
    console.log(`[${time}] [FATAL] - ${logs}`.magenta);
}

exports.koa = koa;
exports.debug = debug;